/**
 * 深度优先算法 - 二叉树的直径
 */
#include <iostream>
using namespace std;

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right)
        : val(x), left(left), right(right) {}
};

class Solution {
public:
    int ans;
    /**
     *  ★★★  思想： 找到一个节点（并非一定是根节点）左子树深度 + 右子树深度最大。
     */
    int depth(TreeNode *rt) {
        if (rt == NULL) {
            return 0;  // 访问到空节点了，返回0
        }
        int L = depth(rt->left);    // 左儿子为根的子树的深度
        int R = depth(rt->right);   // 右儿子为根的子树的深度
        ans = max(ans, L + R + 1);  // 计算d_node即L+R+1 并更新ans
        return max(L, R) + 1;       // 返回该节点为根的子树的深度
    }
    int diameterOfBinaryTree(TreeNode *root) {
        ans = 1;
        depth(root);
        return ans - 1;
    }
};

int main() {
    Solution s;
    TreeNode *tree = new TreeNode(1);
    tree->left = new TreeNode(5);
    tree->right = new TreeNode(2);
    tree->left->left = new TreeNode(3);
    tree->left->right = new TreeNode(4);
    tree->left->right->left = new TreeNode(7);
    s.diameterOfBinaryTree(tree);
    cout << s.ans << endl;
    return 0;
}